import {Component, OnInit, OnDestroy, AfterViewInit} from '@angular/core';
import {Router, NavigationStart} from '@angular/router';

import {PerformanceMonitoringService} from '@kylin/core';
import {SkinService} from '@kylin/core';
import {KylinRouteReuseStrategy} from './core/service/kylinRouteReuseStrategy';

@Component({
    selector: 'kylin-root',
    templateUrl: './app.component.html',
    providers: [KylinRouteReuseStrategy]
})
export class AppComponent implements OnInit, OnDestroy, AfterViewInit {
    constructor(private PMService: PerformanceMonitoringService,
                private skinService: SkinService,
                private router: Router) {
        this.PMService.init();
        this.skinInit();

    }

    private lastRouterUrl = '';

    ngOnInit() {
        this.$routeSnapshotHandler();
    }

    ngAfterViewInit() {

    }

    ngOnDestroy() {
        this.PMService.destroy();
    }

    private skinInit() {
        const defaultSkinColor = this.skinService.defaultSkinColor();
        const targetColor = this.skinService.getSkinColor();
        if (targetColor && targetColor !== defaultSkinColor) {
            this.skinService.change(targetColor);
        }
    }

    /**
     * 当路由变化,处理是否使用路由快照
     * 处理逻辑: 当目标页面开启路由缓存 data: {routeReuseStrategy: true} 且目标页面为当前页面父级,那么就使用之前的页面缓存.否则就清空之前的目标页面缓存,生成全新的页面
     */
    $routeSnapshotHandler() {
        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this.lastRouterUrl) {
                    const currentRouterUrl = event.url;
                    if (this.lastRouterUrl.indexOf(currentRouterUrl) === -1) {
                        this.deleteRouteSnapshot(currentRouterUrl);
                    }
                }
                this.lastRouterUrl = event.url;
            }
        });
    }

    /**
     * 路由加载前可手动删除路由快照，切换路由则不会使用快照
     */
    private deleteRouteSnapshot(url: string) {
        const targetRouteSnapshotKey = url.replace(/\//g, '_'); // 此key名称处理逻辑和kylinRouteReuseStrategy.ts文件内命名逻辑一致,修改请注意
        KylinRouteReuseStrategy.deleteRouteSnapshot(targetRouteSnapshotKey);
    }
}
